import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:raze/lore/chronicle/user_chronicle.dart';
import 'package:raze/lore/chronicle/whisper_chronicle.dart';
import 'package:raze/artifacts/clickable_avatar_widget.dart';
import 'package:raze/lore/glyph/user_essence.dart';
import 'package:raze/lore/glyph/whisper_essence.dart';
import 'package:raze/potions/raze_constant.dart';
import 'package:raze/potions/spatial_alchemy.dart';

/// 消息会话项数据模型
class ConversationEcho {
  final UserEssence otherUser;
  final WhisperEssence latestMessage;
  final int unreadCount;

  ConversationEcho({
    required this.otherUser,
    required this.latestMessage,
    required this.unreadCount,
  });
}

/// 消息列表页面
class MessageListRealms extends StatelessWidget {
  const MessageListRealms({super.key});

  @override
  Widget build(BuildContext context) {
    final userChronicle = Get.find<UserChronicle>();
    final whisperChronicle = Get.find<WhisperChronicle>();

    return Container(
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage('assets/images/background.png'),
          fit: BoxFit.cover,
        ),
      ),
      child: Scaffold(
        backgroundColor: Colors.transparent,
        body: Column(
          children: [
            // 顶部导航栏
            _assembleTopNavigationBar(),

            // 消息列表
            Expanded(
              child: Obx(() {
                final currentUser = userChronicle.currentUser;
                if (currentUser == null) {
                  return Center(
                    child:
                        Text('Please login first')
                            .applyTypeSize(16.sp)
                            .applyTypeColor(RazeConstants.black)
                            .applyNotoSans(),
                  );
                }

                // 获取对话列表
                final conversations = _gatherConversationList(
                  currentUser.id,
                  whisperChronicle,
                  userChronicle,
                );

                if (conversations.isEmpty) {
                  return Center(
                    child:
                        Text('No messages yet')
                            .applyTypeSize(16.sp)
                            .applyTypeColor(RazeConstants.black)
                            .applyNotoSans(),
                  );
                }

                return ListView.builder(
                  padding: EdgeInsets.symmetric(
                    horizontal: 16.w,
                    vertical: 16.h,
                  ),
                  itemCount: conversations.length,
                  itemBuilder: (context, index) {
                    final conversation = conversations[index];
                    return _constructConversationItem(conversation);
                  },
                );
              }),
            ),
          ],
        ),
      ),
    );
  }

  /// 组装顶部导航栏
  Widget _assembleTopNavigationBar() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
      child: SafeArea(
        bottom: false,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            // 返回按钮
            Container(
                  width: 30.w,
                  height: 30.w,
                  decoration: BoxDecoration(
                    color: RazeConstants.background,
                    borderRadius: BorderRadius.circular(8.r),
                    border: Border.all(
                      color: RazeConstants.black,
                      width: 1.5.w,
                    ),
                  ),
                  child: Icon(
                    Icons.chevron_left_rounded,
                    size: 24.sp,
                    color: RazeConstants.black,
                  ),
                )
                .withRightBottomShadow(thickness: 1)
                .withTouchResonance(onTap: () => Get.back()),

            // 标题
            Text('Message')
                .applyTypeSize(24.sp)
                .applyTypeColor(RazeConstants.black)
                .applyBagelFatOne(weight: FontWeight.w400),

            // 占位，保持标题居中
            30.w.boxWidth,
          ],
        ),
      ),
    );
  }

  /// 收集对话列表
  /// 将消息按对方用户分组，获取最新消息和未读数
  List<ConversationEcho> _gatherConversationList(
    String currentUserId,
    WhisperChronicle whisperChronicle,
    UserChronicle userChronicle,
  ) {
    final allMessages = whisperChronicle.messageList;
    final conversationMap = <String, ConversationEcho>{};

    // 找出所有与当前用户相关的对话
    for (final message in allMessages) {
      String? otherUserId;

      if (message.senderId == currentUserId) {
        otherUserId = message.receiverId;
      } else if (message.receiverId == currentUserId) {
        otherUserId = message.senderId;
      }

      if (otherUserId == null) continue;

      // 如果已有该用户的对话记录，检查是否需要更新
      if (conversationMap.containsKey(otherUserId)) {
        final existing = conversationMap[otherUserId]!;
        if (message.createTime.isAfter(existing.latestMessage.createTime)) {
          final unreadCount = whisperChronicle.countUnreadMessages(
            currentUserId,
            otherUserId,
          );
          conversationMap[otherUserId] = ConversationEcho(
            otherUser: existing.otherUser,
            latestMessage: message,
            unreadCount: unreadCount,
          );
        }
      } else {
        // 新对话
        final otherUser = userChronicle.queryUserById(otherUserId);
        if (otherUser != null) {
          final unreadCount = whisperChronicle.countUnreadMessages(
            currentUserId,
            otherUserId,
          );
          conversationMap[otherUserId] = ConversationEcho(
            otherUser: otherUser,
            latestMessage: message,
            unreadCount: unreadCount,
          );
        }
      }
    }

    // 转为列表并按最新消息时间排序
    final conversations = conversationMap.values.toList();
    conversations.sort(
      (a, b) =>
          b.latestMessage.createTime.compareTo(a.latestMessage.createTime),
    );

    return conversations;
  }

  /// 构建对话列表项
  Widget _constructConversationItem(ConversationEcho conversation) {
    return Container(
      margin: EdgeInsets.only(bottom: 16.h),
      padding: EdgeInsets.only(
        left: 12.w,
        right: 12.w,
        top: 10.h,
        bottom: 16.h,
      ),
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage('assets/images/message-background.png'),
          fit: BoxFit.fill,
        ),
      ),
      child: Row(
        children: [
          // 用户头像
          ClickableAvatarWidget(
            userId: conversation.otherUser.id,
            avatarPath: conversation.otherUser.avatar,
            width: 46.w,
            height: 46.w,
          ),
          12.w.boxWidth,

          // 用户名和最新消息
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 用户名
                Text(conversation.otherUser.username)
                    .applyTypeSize(16.sp)
                    .applyTypeColor(RazeConstants.black)
                    .applyBagelFatOne(weight: FontWeight.w400),
                4.h.boxHeight,

                // 最新消息内容
                Text(
                      _renderMessagePreview(conversation.latestMessage),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    )
                    .applyTypeSize(13.sp)
                    .applyTypeColor(RazeConstants.black.withOpacity(0.6))
                    .applyNotoSans(),
              ],
            ),
          ),

          // 未读消息数（有占位）
          SizedBox(
            width: 40.w,
            child:
                conversation.unreadCount > 0
                    ? Container(
                      padding: EdgeInsets.symmetric(
                        horizontal: 6.w,
                        vertical: 2.h,
                      ),
                      decoration: BoxDecoration(
                        color: RazeConstants.lightBlue,
                        borderRadius: BorderRadius.circular(12.r),
                        border: Border.all(
                          color: RazeConstants.black,
                          width: 1.5.w,
                        ),
                      ),
                      child: Center(
                        child: Text(
                          conversation.unreadCount > 99
                              ? '99+'
                              : conversation.unreadCount.toString(),
                          style: TextStyle(
                            color: RazeConstants.black,
                            fontSize: 12.sp,
                            fontWeight: FontWeight.w700,
                          ),
                        ),
                      ),
                    )
                    : const SizedBox.shrink(),
          ),
        ],
      ),
    ).withTouchResonance(
      onTap: () {
        // 跳转到单聊页面
        Get.toNamed(
          '/single-chat',
          parameters: {'otherUserId': conversation.otherUser.id},
        );
      },
    );
  }

  /// 渲染消息预览文本
  String _renderMessagePreview(WhisperEssence message) {
    if (message.messageType == 'call_failed') {
      return 'Missed call';
    }
    return message.content;
  }
}
